<template>
  <div>
    <el-card>
      <div slot="header" class="clearfix">
        <span>{{title}}</span>
        <el-button class="fr" style="padding: 3px 0" type="text" @click="handleOpen" v-if="isEditSelect">选择</el-button>
        <el-button class="fr" style="padding: 3px 0" type="text" v-if="isEditPack" @click="againPack">打包</el-button>
      </div>
      <template v-for="(item,index) in resultData">
        <template v-if="item.boxNo">
          <el-card class="fl mr10 mb10" style="width: 45%" >
            <el-descriptions :column="3" border :labelStyle="centerText">
              <el-descriptions-item label="箱号" :span="2">{{item.boxNo}}</el-descriptions-item>
              <el-descriptions-item label="物品数">
                 <i>{{item.nums}}</i>
                 <el-tooltip content="拆箱" placement="top" effect="light" class="mr10 ml10" v-if="isEditPack">
                   <el-popover
                     placement="top"
                     width="160"
                     v-model="item.isRemove">
                     <p>是否拆箱？</p>
                     <div style="text-align: right; margin: 0">
                       <el-button size="mini" type="text" @click="item.isRemove = false">取消</el-button>
                       <el-button type="primary" size="mini" @click="dismantleBox(item,index)">确定</el-button>
                     </div>
                     <el-button slot="reference" type="text" style="color: red;" icon="el-icon-box" ></el-button>
                   </el-popover>
                 </el-tooltip>
                  <el-tooltip content="整箱移除" placement="top" effect="light" class="mr10 ml10" v-if="isEditSelect">
                    <el-popover
                      placement="top"
                      width="160"
                      v-model="item.isRemove">
                      <p>是否移除该货箱？</p>
                      <div style="text-align: right; margin: 0">
                        <el-button size="mini" type="text" @click="item.isRemove = false">取消</el-button>
                        <el-button type="primary" size="mini" @click="removeBox(item,index)">确定</el-button>
                      </div>
                      <el-button slot="reference" type="text" style="color: red;" icon="el-icon-delete" ></el-button>
                    </el-popover>
                  </el-tooltip>
                  <el-tooltip content="新增物品" effect="light" placement="top" v-if="isEditSelect">
                    <el-button type="text" icon="el-icon-circle-plus-outline" @click="addBoxItems(item)"></el-button>
                  </el-tooltip>
              </el-descriptions-item>
              <template v-for="(child,ind) in item.items">
                <el-descriptions-item label="编号" :span="3">
                {{child.pno}}
                <el-tooltip content="移除" placement="top" effect="light" v-if="isEditSelect">
                  <el-popover
                    placement="top"
                    width="160"
                    v-model="child.isRemove">
                    <p>是否移除该物品？</p>
                    <div style="text-align: right; margin: 0">
                      <el-button size="mini" type="text" @click="child.isRemove = false">取消</el-button>
                      <el-button type="primary" size="mini" @click="removeBoxItems(child,ind,item.items,index)">确定</el-button>
                    </div>
                    <el-button slot="reference" type="text" style="color: red;" icon="el-icon-remove-outline" ></el-button>
                  </el-popover>
                </el-tooltip>
                </el-descriptions-item>
                <el-descriptions-item label="名称" :span="2">{{child.name}}</el-descriptions-item>
                <el-descriptions-item label="数量" :span="1">{{child.nums}}</el-descriptions-item>
              </template>
              <template v-if="isShowStore">
                <el-descriptions-item label="仓库" :span="3">{{item.storeName}}</el-descriptions-item>
                <el-descriptions-item label="存放位置" :span="3">
                  <locator-select :item="item" v-if="isShowArea"></locator-select>
                  <p v-if="!isShowArea">{{(item.areaName?item.areaName+'/':'')+(item.locatorName?item.locatorName:'')}}</p>
                </el-descriptions-item>
              </template>
            </el-descriptions>
          </el-card>
        </template>
        <template v-if="!item.boxNo">
          <el-card class="fl mr10 mb10">
            <el-descriptions :column="3" border :labelStyle="centerText">
               <el-descriptions-item label="编号" :span="3">
                  <el-checkbox slot="label" v-if="mode == 'putTask' || mode == 'pick'" :checked="item.isChecked" @change="checkboxChange($event,item)"></el-checkbox>
                  {{item.pno}}
               <el-tooltip content="移除" placement="top" effect="light" v-if="isEditSelect">
                 <el-popover
                   placement="top"
                   width="160"
                   v-model="item.isRemove">
                   <p>是否移除该物品？</p>
                   <div style="text-align: right; margin: 0">
                     <el-button size="mini" type="text" @click="item.isRemove = false">取消</el-button>
                     <el-button type="primary" size="mini" @click="removeDtl(item,index)">确定</el-button>
                   </div>
                   <el-button slot="reference" type="text" style="color: red;" icon="el-icon-remove-outline" ></el-button>
                 </el-popover>
               </el-tooltip>
               </el-descriptions-item>
               <el-descriptions-item label="名称" :span="2">{{item.name}}</el-descriptions-item>
               <el-descriptions-item label="数量">{{item.nums}}</el-descriptions-item>
               <el-descriptions-item label="附件" :span="3">
                 <el-image v-if="item.pics"
                   style="width: 120px; height: 60px;margin-right: 5px;" :src="item.pics.split(',')[0]" fit="scale-down"
                   :preview-src-list="item.pics.split(',')"></el-image>
               </el-descriptions-item>
               <template v-if="isShowStore">
                 <el-descriptions-item label="仓库" :span="3">{{item.storeName}}</el-descriptions-item>
                 <el-descriptions-item label="存放位置" :span="3">
                   <locator-select :item="item" v-if="isShowArea"></locator-select>
                   <p v-if="!isShowArea">{{(item.areaName?item.areaName+'/':'')+(item.locatorName?item.locatorName:'')}}</p>
                 </el-descriptions-item>
               </template>
            </el-descriptions>
          </el-card>
        </template>
      </template>
    </el-card>
    <el-drawer :visible.sync="show" :before-close="handleClose" destroy-on-close size="70vw">
      <div class="mainDiv">
        <el-container class="main_container">
          <el-header>
            <p style="font-size: 22px;">物品列表</p>
          </el-header>
          <el-main>
            <el-row :gutter="20">
              <el-col :span="4" :xs="6">
                <div class="head-container">
                  <el-input v-model="classifyName" placeholder="请输入分类名称" clearable size="small" prefix-icon="el-icon-search" class="mb10" />
                </div>
                <div class="head-container">
                  <el-tree :data="classifyOptions" :props="defaultProps" :expand-on-click-node="false" accordion
                    :filter-node-method="filterNode" ref="tree" @node-click="handleNodeClick" />
                </div>
              </el-col>
              <el-col :span="20" :xs="18">
                <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="80px">
                  <el-form-item label="物品编号" prop="pno">
                    <el-input v-model="queryParams.pno" placeholder="请输入物品编号" clearable size="small"
                      @keyup.enter.native="handleQuery" />
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                    <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                  </el-form-item>
                </el-form>
                <el-table v-loading="loading" :data="inventoryList" @selection-change="handleSelectionChange" border>
                  <el-table-column type="selection" width="55" align="center" fixed="left"/>
                  <el-table-column label="编号" align="center" prop="pno" width="240" fixed="left"/>
                  <el-table-column label="名称" prop="name"  width="180" fixed="left"/>
                  <el-table-column label="部门" prop="deptName"  width="260"/>
                  <el-table-column label="仓库" prop="store" width="260"/>
                  <el-table-column label="库区"  prop="area" width="120"/>
                  <el-table-column label="库位" prop="locator" width="120"/>

                  <!-- <el-table-column label="入库时间" align="center" prop="intime" width="180">
                    <template slot-scope="scope">
                      <span>{{ parseTime(scope.row.intime) }}</span>
                    </template>
                  </el-table-column> -->
                  <el-table-column label="库存数量" align="center" prop="nums" width="80" />
                  <el-table-column label="状态" align="center" prop="status" width="80">
                    <template slot-scope="scope">
                      <dict-tag :options="dict.type.wms_stock_status" :value="scope.row.status" />
                    </template>
                  </el-table-column>
                </el-table>
                <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                  @pagination="getList" />
              </el-col>
            </el-row>
          </el-main>
          <el-footer class="footerDivClass">
            <el-button type="warning" :disabled="multiple" @click="handlePack" v-if="isPack">打 包</el-button>
            <el-button type="primary" :disabled="multiple" @click="handleSumbit" >确 定</el-button>
            <el-button @click="handleClose()">取 消</el-button>
          </el-footer>
        </el-container>
      </div>
    </el-drawer>
    <el-dialog title="货箱选择"  :visible.sync="boxShow" width="880px"  :before-close="handleBoxClose">
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-row :gutter="15">
          <!-- <el-col :span="10">
            <el-form-item label="箱名" prop="boxId">
              <el-select v-model="form.boxId" placeholder="请选择箱名" @change="boxChange">
                <el-option v-for="item in boxOptions" :key="item.id" :label="item.name" :value="item.id">
                  <span style="float: left">{{ item.name }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.boxNo }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
          <el-col>
            <el-form-item label="箱号" prop="boxNo">
              <el-input v-model="form.boxNo" placeholder="请输入箱号"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-table :data="form.items" border>
              <el-table-column label="编号" align="center" prop="pno"></el-table-column>
              <el-table-column label="名称" align="center" prop="name"></el-table-column>
              <el-table-column label="数量" align="center" prop="nums"></el-table-column>
            </el-table>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="boxSumbit" v-if="isEditSelect">确 定</el-button>
        <el-button :loading="buttonLoading" type="primary" @click="againBoxSumbit" v-if="isEditPack">确 定</el-button>
        <el-button @click="handleBoxClose">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {treeselect} from "@/api/oms/classify"
  import {listProperty} from "@/api/oms/property"
  import {listInventory} from "@/api/wms/inventory"
  import {listBox} from "@/api/oms/box"
  import {delDtl} from "@/api/oms/task"
  import {delUnpacking } from "@/api/wms/putTask";
  export default {
    dicts:['wms_stock_status'],
    props:{
      //接收参数
      value:{
        type:[String,Object,Array]
      },
      //标题
      title:{
        type:[String],
        default:'物品清单'
      },
      //模式:normal、putTask、pick
      mode:{
        type:[String],
        default:'normal'
      },
      //是否显示打包按钮
      isPack:{
        type:[Boolean],
        default:true
      },
      putTaskId:{
        type:[String],
        default:undefined
      },
      deptId:{
        type:[Number]
      }
    },
    data() {
      return{
        //弹窗显示
        show:false,
        //对话框显示
        boxShow:false,

        //分类数据
        classifyOptions:[],
        //分类筛选
        classifyName:undefined,
        defaultProps: {
          children: "children",
          label: "label"
        },

        //库存数据
        inventoryList:[],
        // 总条数
        total: 0,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          pno:undefined,
          classifyId:undefined,
          secondClassifyId:undefined,
          thirdClassifyId:undefined,
          status: '0',
          delFlag: '0'
        },
        loading:true,
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,

        //多选值数据
        dataList:[],

        //返回的参数
        resultData:[],

        //样式
        centerText:{
          'textAlign':'center',
        },
        //card上的打包
        isEditPack:false,
        //card上的选择
        isEditSelect:false,
        //是否展示仓库
        isShowStore:false,
        //是否展示库区选择
        isShowArea:true,

        //装箱数据
        form:{},
        //规则
        rules:{
          boxId: [{
            required: true,
            message: "箱名不能为空",
            trigger: "blur"
          }],
          boxNo: [{
            required: true,
            message: "箱号不能为空",
            trigger: "blur"
          }],
        },
        //货箱数据
        boxOptions:[],

        //按钮
        buttonLoading:false,
        //箱内添加物品
        addBoxForm:{},

        //打包数据
        selectionList:[]
      }
    },
    watch:{
      classifyName(val) {
        this.$refs.tree.filter(val);
      },
      value(val){
        this.resultData = val;
      },
      mode(val){
        this.modeChange(val);
      },
      deptId(val){
        if(val){
          this.queryParams.deptId = val;
          this.getList();
        }
      }
    },
    created() {
      this.getList();
      this.getClassifyTreeselect();
      this.modeChange(this.mode)
    },
    methods:{
      /** 查询库存数据 */
      getList(){
        this.loading = true;
        listProperty(this.queryParams).then(response=>{
          this.inventoryList = response.rows;
          this.total = response.total;
          this.loading = false;
        })
      },
      /** 切换模式 */
      modeChange(mode){
        if(mode == 'normal'){
          this.isEditSelect = true;
        }
        if(mode == 'putTask'){
          this.isEditSelect = false;
          this.isEditPack = true;
          this.isShowStore = true;
          this.isShowArea = true;
        }
        if(mode == 'pick'){
          this.isEditSelect = false;
          this.isEditPack = true;
          this.isShowStore = true;
          this.isShowArea = false;
        }
      },
      /** 数据筛选 */
      /** 查询分类下拉树结构 */
      getClassifyTreeselect() {
        treeselect().then(response => {
          this.classifyOptions = response.data;
        });
      },
      // 筛选节点
      filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
      },
      // 节点单击事件
      handleNodeClick(data) {
        if(data.weight == 0){
          this.queryParams.classifyId = data.id;
          this.queryParams.secondClassifyId = undefined;
          this.queryParams.thirdClassifyId = undefined;
        }
        if(data.weight == 1){
          this.queryParams.classifyId = undefined;
          this.queryParams.secondClassifyId = data.id;
          this.queryParams.thirdClassifyId = undefined;
        }
        if(data.weight == 2){
          this.queryParams.classifyId = undefined;
          this.queryParams.secondClassifyId = undefined;
          this.queryParams.thirdClassifyId = data.id;
        }
        this.handleQuery();
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.queryParams.classifyId = undefined;
        this.queryParams.secondClassifyId = undefined;
        this.queryParams.thirdClassifyId = undefined;
        this.resetForm("queryForm");
        this.handleQuery();
      },
      /** 多选框选中数据 */
      handleSelectionChange(selection) {
        if(this.resultData != null){
          let boxResult = this.box2Dtl(this.resultData);
          selection.forEach(child=>{
            boxResult[0].forEach(item=>{
              if(item.pno == child.pno){
                this.$modal.msgError("编号"+item.pno+'已添加到物品清单，请忽重复添加');
                return
              }
            })
          })
        }
        this.dataList = [];
        selection.forEach(item=>{
          item.id = undefined;
          this.dataList.push(item);
        })
        this.multiple = !selection.length
      },
      /** 多选数据 */
      checkboxChange(selection,item){
        if(selection){
          this.dataList.push(item)
        }else{
          this.dataList.forEach((data,index)=>{
            if(data.pno == item.pno){
              this.dataList.splice(index,1)
            }
          })
        }
      },
      /** 重新打包 */
      againPack(){
        if(this.dataList.length == 0){
          this.$modal.msg("请至少选择一条物品");
          return false;
        }
        this.handlePack();
      },

      /** 重新打包--确认 */
      againBoxSumbit(){
        let boxResults = this.box2Dtl(this.resultData)
        let form = this.form
        boxResults[0].forEach(item=>{
          form.items.forEach(child=>{
            if(child.pno == item.pno){
              item.boxId = form.boxId;
              item.boxNo = form.boxNo;
            }
          })
        })
        this.resultData = this.dtl2Box(boxResults[0],item=>item.boxId)
        this.$emit('input',this.resultData)
        this.handleBoxClose();
      },
      //箱号重置
      reset(){
        this.form = {
          boxId:undefined,
          boxNo:undefined,
          nums:0,
          items:[],
          delFlag:'0'
        }
        this.resetForm('form')
      },
      /** 打包选择货箱 */
      handlePack(){
        this.reset();
        this.form.items = this.dataList;
        this.boxShow = true;
        // listBox({status:'0'}).then(response=>{
        //   this.boxOptions = response.rows;
        //   this.boxShow = true;
        //   this.form.items = this.dataList;
        // })
      },
      // 箱号选择
      boxChange(e){
        this.boxOptions.forEach(item=>{
          if(item.id == e){
            this.form.boxNo = item.boxNo;
          }
        })
      },
      /** 默认选择 */
      handleSumbit(){
        if(this.addBoxForm.boxId){
          let items = this.addBoxForm.items;
          this.dataList.forEach(item=>{
            let flag = true;
             items.forEach(child=>{
               if(child.pno == item.pno){
                 flag = false;
                 return
               }
             })
             if(flag){
               items.push(item)
             }
          })
        }else{
          this.dataList.forEach(item=>{
             let flag = true;
             if(this.resultData != null){
              let boxResult = this.box2Dtl(this.resultData);
               boxResult[0].forEach(child=>{
                 if(child.pno == item.pno){
                   flag = false;
                   return
                 }
               })
             }else{
               this.resultData = [];
             }
             if(flag){
               this.resultData.push(item)
             }
          })
        }
        this.$emit('input',this.resultData)
        this.handleClose();
      },
      /** 装箱确认 */
      boxSumbit(){
        this.buttonLoading = true;
        this.$refs["form"].validate(valid=>{
          if(valid){
            let form = this.form;
            let items = form.items;
            let nums = 0;
            items.forEach(item=>{
              nums+= item.nums;
            })
            form.nums = nums;
            let data = {
              boxId:form.boxId,
              boxNo:form.boxNo,
              nums:form.nums,
              items:form.items,
              delFlag:'0'
            }
            if(this.resultData == null){
              this.resultData = [];
            }
            this.resultData.push(data)
            this.handleClose();
            this.handleBoxClose();
            this.buttonLoading = false;
          }else{
            this.buttonLoading = false;
          }
          this.$emit('input',this.resultData)
        })
      },
      /** 功能信息 */
      //删除物品
      removeDtl(data,index){
        if(data.id){
          delDtl({items:[data]});
        }
        this.resultData.splice(index,1)
      },
      //删除箱子
      removeBox(data,index){
        let items = data.items;
        let delItems = [];
        items.forEach(item=>{
          if(item.id){
            delItems.push(item)
          }
        })
        if(delItems.length == 0){
        	this.resultData.splice(index,1)
        }else{
          let boxList = [];
          boxList.push({id:data.boxId})
          delDtl({items:delItems,boxList:boxList}).then(response=>{
            this.resultData.splice(index,1)
          })
        }
      },
      //拆箱
      dismantleBox(data,index){
        let delBoxIds = [];
        let boxResults = this.box2Dtl(this.resultData)
        boxResults[0].forEach(item=>{
          if(data.boxId == item.boxId){
            if(!delBoxIds.includes(item.boxId)){
              delBoxIds.push(item.boxId)
            }
            item.boxId = undefined;
            item.boxNo = undefined;
            item.isChecked = false;
          }
        })
        this.resultData = this.dtl2Box(boxResults[0],item=>item.boxId)
        return delUnpacking(delBoxIds,this.putTaskId)
      },
      //删除箱子内的物品
      removeBoxItems(data,ind,list,index){
        if(data.id){
          let boxList = [];
          boxList.push({id:data.boxId})
          if(list.length ==1){
            this.resultData.splice(index,1)
          }
          delDtl({items:[data]})
        }
        list.splice(ind,1)
      },
      //添加箱内物品
      addBoxItems(data){
        this.addBoxForm = data;
        this.handleOpen();
      },
      //打开弹窗
      handleOpen(){
        this.show = true;
      },
      //关闭弹窗
      handleClose(){
        this.show = false;
      },
      //关闭对话框
      handleBoxClose(){
        this.boxShow = false;
      }
    }
  }
</script>

<style>
</style>
